#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
角色管理器
负责角色的创建、保存和加载
"""

import json
import os
from typing import List, Optional, Dict, Any
from .character import Character

class CharacterManager:
    """
    角色管理器
    """
    
    def __init__(self, save_path: str = "data/characters.json"):
        """
        初始化角色管理器
        
        Args:
            save_path: 角色数据保存路径
        """
        self.save_path = save_path
        self.characters: Dict[str, Character] = {}
        self.current_character: Optional[Character] = None
        
        # 确保数据目录存在
        os.makedirs(os.path.dirname(save_path), exist_ok=True)
        
        # 加载已有角色数据
        self.load_characters()
    
    def create_character(self, name: str, character_class: str = "战士") -> tuple[bool, str, Optional[Character]]:
        """
        创建新角色
        
        Args:
            name: 角色名称
            character_class: 角色职业
            
        Returns:
            (成功标志, 消息, 角色对象)
        """
        # 检查角色名是否已存在
        for character in self.characters.values():
            if character.name == name:
                return False, f"角色名 '{name}' 已存在", None
        
        # 创建新角色
        character = Character(name, character_class)
        self.characters[character.id] = character
        
        # 保存数据
        self.save_characters()
        
        return True, f"角色 '{name}' 创建成功", character
    
    def get_character_by_id(self, character_id: str) -> Optional[Character]:
        """
        根据ID获取角色
        """
        return self.characters.get(character_id)
    
    def get_character_by_name(self, name: str) -> Optional[Character]:
        """
        根据名称获取角色
        """
        for character in self.characters.values():
            if character.name == name:
                return character
        return None
    
    def get_all_characters(self) -> List[Character]:
        """
        获取所有角色
        """
        return list(self.characters.values())
    
    def select_character(self, character_id: str) -> tuple[bool, str]:
        """
        选择当前角色
        
        Args:
            character_id: 角色ID
            
        Returns:
            (成功标志, 消息)
        """
        character = self.get_character_by_id(character_id)
        if not character:
            return False, "角色不存在"
        
        self.current_character = character
        return True, f"已选择角色: {character.name}"
    
    def delete_character(self, character_id: str) -> tuple[bool, str]:
        """
        删除角色
        
        Args:
            character_id: 角色ID
            
        Returns:
            (成功标志, 消息)
        """
        character = self.get_character_by_id(character_id)
        if not character:
            return False, "角色不存在"
        
        # 如果删除的是当前角色，清空当前角色
        if self.current_character and self.current_character.id == character_id:
            self.current_character = None
        
        del self.characters[character_id]
        self.save_characters()
        
        return True, f"角色 '{character.name}' 已删除"
    
    def save_characters(self):
        """
        保存角色数据到文件
        """
        try:
            data = {
                'characters': {cid: char.to_dict() for cid, char in self.characters.items()},
                'current_character_id': self.current_character.id if self.current_character else None
            }
            
            with open(self.save_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
                
        except Exception as e:
            print(f"保存角色数据失败: {e}")
    
    def load_characters(self):
        """
        从文件加载角色数据
        """
        try:
            if not os.path.exists(self.save_path):
                return
            
            with open(self.save_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            # 加载角色
            self.characters = {}
            for cid, char_data in data.get('characters', {}).items():
                character = Character.from_dict(char_data)
                self.characters[cid] = character
            
            # 设置当前角色
            current_character_id = data.get('current_character_id')
            if current_character_id and current_character_id in self.characters:
                self.current_character = self.characters[current_character_id]
                
        except Exception as e:
            print(f"加载角色数据失败: {e}")
    
    def get_character_classes(self) -> List[str]:
        """
        获取可选的角色职业
        """
        return ["战士", "法师", "弓箭手", "刺客", "牧师"]
    
    def get_character_stats(self) -> Dict[str, Any]:
        """
        获取角色统计信息
        """
        total_characters = len(self.characters)
        max_level = max([char.level for char in self.characters.values()]) if self.characters else 0
        
        class_counts = {}
        for character in self.characters.values():
            class_counts[character.character_class] = class_counts.get(character.character_class, 0) + 1
        
        return {
            'total_characters': total_characters,
            'max_level': max_level,
            'class_distribution': class_counts,
            'current_character': self.current_character.name if self.current_character else None
        }